package pri.hillchen.std.concurrent.chapter5;

import java.io.File;
import java.io.FileFilter;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by hillchen on 2018/2/7.
 */
public class FileCawlerDemo {
    class FileCrawler implements Runnable{
        private final Map<String,Boolean> crawlerFiles = new ConcurrentHashMap<String, Boolean>();
        private final BlockingQueue<File> dirQueue;
        private final File root;

        public FileCrawler(BlockingQueue<File> dirQueue, File root) {
            this.dirQueue = dirQueue;
            this.root = root;
        }

        @Override
        public void run(){
            try {
                crawl(root);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        private void crawl(File root) throws InterruptedException {
            File[] files = root.listFiles();
            if(files!=null){
                for(File file : files){
                    if(!alreadyIndexed(file)){
                        dirQueue.put(file);
                        crawlerFiles.put(file.getAbsolutePath(),true);
                    }
                    if(file.isDirectory()){
                        crawl(file);
                    }
                }
            }
        }
        private boolean alreadyIndexed(File file){
            return crawlerFiles.containsKey(file.getAbsolutePath());
        }
    }

    class PrintFile implements Runnable{
        private final BlockingQueue<File> fileQueue;
        private final ConcurrentHashMap<String,File> resultFiles;
        private final FileFilter fileFilter;

        public PrintFile(BlockingQueue<File> fileQueue, FileFilter fileFilter, ConcurrentHashMap<String, File> resultFiles) {
            this.fileQueue = fileQueue;
            this.resultFiles = resultFiles;
            this.fileFilter = fileFilter;
        }

        public void run() {
            try {
                while (true){
                    File file = fileQueue.take();
                    if(fileFilter.accept(file)){
                        resultFiles.put(file.getAbsolutePath(),file);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
